package com.atguigu.mr.flow;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

/**
 * @description: 读取文件统计用户上行/下行流量.
 * @create: 2019-12-15 22:06
 * @author: baojinlong
 **/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FlowBean implements Writable, WritableComparable<FlowBean> {
    private long upFlow;
    private long downFlow;
    private long sumFlow;

    /**
     * 序列化方法
     *
     * @param out
     * @throws IOException
     */
    @Override
    public void write(DataOutput out) throws IOException {
        out.writeLong(upFlow);
        out.writeLong(downFlow);
        out.writeLong(sumFlow);
    }

    /**
     * 反序列化方法
     *
     * @param in
     * @throws IOException
     */
    @Override
    public void readFields(DataInput in) throws IOException {
        // 跟序列化方法顺序需要一致.
        upFlow = in.readLong();
        downFlow = in.readLong();
        sumFlow = in.readLong();
    }

    /**
     * 最终输出到text中数据
     *
     * @return
     */
    @Override
    public String toString() {
        return "FlowBean{" +
                "upFlow=" + upFlow +
                ", downFlow=" + downFlow +
                ", sumFlow=" + sumFlow +
                '}';
    }

    @Override
    public int compareTo(FlowBean flowBean) {
        int result = 0;
        // 按照总流量大小，倒序排列
        if (sumFlow > flowBean.getSumFlow()) {
            result = -1;
        } else if (sumFlow < flowBean.getSumFlow()) {
            result = 1;
        } else {
            // 按照上行流量的正序排序
            if (upFlow > flowBean.upFlow) {
                return 1;
            } else if (upFlow < flowBean.upFlow) {
                return -1;
            }
        }
        return result;
    }

    public void set(long downFlow2, long upFlow2) {
        this.downFlow = downFlow2;
        this.upFlow = upFlow2;
        this.sumFlow = downFlow2 + upFlow2;
    }
}
